#include "UDPGroupContainer.h"
#include <QTimer>
#include <QDebug>
#include <QDateTime>
#include "Transmission/UDP/UDPClient.h"
#include "Transmission/UDP/UDPGroup.h"
UDPClient* udp;
UDPGroup* group;

extern uint32_t CreateRef;
extern uint32_t DestroyRef;
int recvcount = 0;
int lastcount = 0;
UDPClient* u;
UDPGroupContainer::UDPGroupContainer(QWidget *parent)
	: QWidget(parent)
	, ui(new Ui::UDPGroupContainerClass())
{
	ui->setupUi(this);
	timer = new QTimer(this);
	connect(timer, &QTimer::timeout, this, &UDPGroupContainer::Tick);
	timer->start(25);

	udp = new UDPClient();
	/*if (!udp->Initialize(5555))
		throw;
	udp->RegisterReceivedCallback(&UDPGroupContainer::OnUDPReceived, this);*/

	group = new UDPGroup();
	if (!group->Initialize())
		throw;
	group->RegisterReceivedCallback(&UDPGroupContainer::OnGroupReceived, this);
	
	if (!group->AddClient(new UDPClient(), 5556))
		throw;


}

UDPGroupContainer::~UDPGroupContainer()
{
	udp->Terminate();
	group->Terminate();
	qDebug() << CreateRef << " " << DestroyRef << " recvcount : " << recvcount;
	delete group;
	delete ui;
}

void UDPGroupContainer::Tick()
{
	if (QDateTime::currentMSecsSinceEpoch() - lastts > 1000)
	{
		lastts = QDateTime::currentMSecsSinceEpoch();
		int delta = recvcount - lastcount;
		lastcount = recvcount;
		qDebug() << CreateRef << " " << DestroyRef << " recvcount : " << delta / 1000 << " kb/s";
		if (u)
			on_RemoveButton_clicked();
		else
			on_InsertButton_clicked();
	}
	/*udp->Update();
	if (!udp->Initialize(5555))
		throw;
	udp->SendTo("a", 1, "127.0.0.1", 5365);*/
	group->Update();
	//udp->Update();
}

void UDPGroupContainer::on_InsertButton_clicked()
{
	u = new UDPClient();
	if (!group->AddClient(u, 5555))
		throw;
}

void UDPGroupContainer::on_RemoveButton_clicked()
{
	group->RemoveClient(u);
	delete u;
	u = nullptr;
}



void UDPGroupContainer::OnUDPReceived(char* buffer, int len, struct sockaddr_in* remote)
{
	/*QByteArray ba(buffer, len);
	qDebug() << ba;*/
	recvcount += len;
	udp->SendTo(buffer, len, remote);
}

void UDPGroupContainer::OnGroupReceived(char* buffer, int len, sockaddr_in* remote, UDPClient* client)
{
	if (!u)
		throw;
	/*QByteArray ba(buffer, len);
	int port;
	client->GetLocalPort(&port);
	qDebug() << port << " : " << ba;*/
	recvcount += len;
	client->SendTo(buffer, 1, remote);
}
